package com.alm.token.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.GoogleAuthKeyData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BindGoogleCodeView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.encode.CodeCreator;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import baibeiwallet.event.RefreshMeEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class BindGoogleCodeActivity extends BaseActivity implements BindGoogleCodeView<GoogleAuthKeyData> {

    @BindView(R.id.tv_googlekey)
    TextView tvGooglekey;
    @BindView(R.id.img_adressqrcode)
    ImageView imgAdressqrcode;
    @BindView(R.id.edt_inputgooglecode)
    EditText edtInputgooglecode;
    @BindView(R.id.tv_registersubmit)
    TextView tvRegistersubmit;
    @BindView(R.id.ly_qrcodebody)
    LinearLayout lyQrcodeBody;
    @BindView(R.id.rly_inputgooglecode_body)
    RelativeLayout rly_inputgooglecode_body;
    private String strGoogleCode;
    public static final int BINDGOOGLECODE_BINd = 1, BINDGOOGLECODE_UNBINd = 2;
    private int type = BINDGOOGLECODE_BINd;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_bind_googlecode;
    }

    @Override
    protected void initVariables() {
        type = getIntent().getIntExtra("BINDGOOGLECODE_type", BINDGOOGLECODE_BINd);
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(
                getString(type == BINDGOOGLECODE_BINd ? R.string.group_hint_Googlecode : R.string.google_title_unbindgooglecode));
        lyQrcodeBody.setVisibility(type == BINDGOOGLECODE_BINd ? View.VISIBLE : View.GONE);
        rly_inputgooglecode_body.setVisibility(type == BINDGOOGLECODE_BINd ? View.GONE : View.VISIBLE);
    }

    @Override
    protected void loadData() {
//        preenter.getcreateCodeData();
        if (type == BINDGOOGLECODE_BINd) {
            preenter.getGoogleAuthKey();
        }

    }


    @Override
    public void onClick(View view) {

    }


    @Override
    public void onError(String error) {
//        showToast(error);
        tvRegistersubmit.setTag(null);
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog(getString(R.string.profile_hint_warn17));
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    public void getData(GoogleAuthKeyData googleAuthKeyData) {
        showToast(googleAuthKeyData.getMsg());
        if (googleAuthKeyData.getStatus() == 0)
            finish();
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void getGoogleAuthKey(GoogleAuthKeyData googleAuthKeyData) {
        if (googleAuthKeyData.getStatus() == 0 && EmptyUtils.isNotEmpty(googleAuthKeyData.getData())) {
            tvGooglekey.setText(googleAuthKeyData.getData());
            initAddressQRCode();
        } else {
            showToast(googleAuthKeyData.getMsg());
        }
    }


    @Override
    public void bindGoogleSecretKey(GoogleAuthKeyData googleAuthKeyData) {
        showToast(googleAuthKeyData.getMsg());
        if (googleAuthKeyData.getStatus() == 0) {
            EventBus.getDefault().post(new RefreshMeEvent(1));
            finish();
        }

    }

    @Override
    public void unbindGoogleSecretKey(GoogleAuthKeyData googleAuthKeyData) {
        showToast(googleAuthKeyData.getMsg());
        if (googleAuthKeyData.getStatus() == 0) {
            EventBus.getDefault().post(new RefreshMeEvent(1));
            finish();
        }
    }

    private Bitmap qrCodeBitmap = null;
    private Bitmap bodyBitmap = null;

    private void initAddressQRCode() {

//        layoutView(lyQrcodeBody,CommonUtil.px2dip(this,470),CommonUtil.px2dip(this,600));
        qrCodeBitmap= null;
        qrCodeBitmap = CodeCreator.createQRCode(tvGooglekey.getText().toString(),
                CommonUtil.dip2px(this, 130),
                CommonUtil.dip2px(this, 130),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        imgAdressqrcode.setImageBitmap(qrCodeBitmap);

        bodyBitmap = CommonUtil.getBitMapFromView(lyQrcodeBody);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.tv_googlekey_copy, R.id.tv_click_saveimg, R.id.tv_registersubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_googlekey_copy:
                if (tvGooglekey.getText().toString() != null) {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setPrimaryClip(ClipData.newPlainText(null, tvGooglekey.getText().toString()));
                    showToast(getString(R.string.profile_hint_item26));
                }
                break;

            case R.id.tv_registersubmit:

                DialogUtils.enterGoogleCode(this, new DialogUtils.IEnterPwdListener() {
                    @Override
                    public void onSuccess(String pwd) {
//                        if (type == BINDGOOGLECODE_BINd) {
                            preenter.bindGoogleSecretKey(pwd);
//                        } else {
//                            preenter.unbindGoogleSecretKey(pwd);
//                        }
                    }
                });

//                if (edtInputgooglecode.getText().toString().isEmpty()) {
//                    showToast(getString(R.string.google_hint_iputgooglecode));
//                    edtInputgooglecode.setFocusable(true);
//                    edtInputgooglecode.setFocusableInTouchMode(true);
//                    edtInputgooglecode.requestFocus();
//                    //显示软键盘
////                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
//                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.showSoftInput(edtInputgooglecode, 0);
//                    break;
//                }
//
//                strGoogleCode = edtInputgooglecode.getText().toString();
//                if (type == BINDGOOGLECODE_BINd) {
//                    preenter.bindGoogleSecretKey(strGoogleCode);
//                } else {
//                    preenter.unbindGoogleSecretKey(strGoogleCode);
//                }

                break;
            case R.id.tv_click_saveimg:
                if (bodyBitmap == null) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                //存储权限
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    if (saveImageToGallery(BindGoogleCodeActivity.this, bodyBitmap, CommonUtil.getStringDate() + getString(R.string.google_hint_creatcode)+".jpg")) {
                                        showToast(getString(R.string.profile_hint_item15));
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });

                break;
        }
    }

    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap   要保存的图片
     * @param fileName 自定义图片名称
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
        //系统相册目录
        String storePath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        // 保存图片至指定路径
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";


        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
